package com.omg.server.crawler.strategy.impl;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.omg.business.model.PostMeta;
import com.omg.business.model.Posts;
import com.omg.business.model.Terms;
import com.omg.business.model.TermsRelation;
import com.omg.business.model.TermsTaxonomy;
import com.omg.server.crawler.strategy.CrawlerStrategy;
import com.omg.server.framework.service.IDefaultService;
import com.omg.server.util.CommonUtil;
import com.omg.server.util.PropertiesHelper;
import com.omg.util.ApplicationContextUtil;
import com.omg.weibo.WeiBoSender;

public class WriteDBUtil {
	private static final Log log = LogFactory.getLog(WriteDBUtil.class);
	private static IDefaultService  defaultService;
	public static void writeToDb(Posts posts, HashSet<PostMeta> postMetas, String type, String tag, 
			       String typeChar, String tagChar, String imgUrl, WeiBoSender wbs){
		if (null == defaultService){
			synchronized (WriteDBUtil.class) {
				if (null == defaultService){
					defaultService = (IDefaultService)ApplicationContextUtil.getBean("common.defaultService");
				}
			}
		}
		
		synchronized (WriteDBUtil.class) {
			
			defaultService.save_Hibernate_Object(posts);
			int postId = posts.getId();
			//System.out.println("postId:" + postId);
			Iterator<PostMeta> it = postMetas.iterator();
			PostMeta pm = null;
			Map<String, Object> params = new HashMap<String, Object>(3);
			while(it.hasNext()){
				pm = it.next();
				params.clear();
				params.put("postId", Integer.valueOf(postId));
				params.put("metaKey", pm.getMetaKey());
				params.put("metaValue", pm.getMetaValue());
				defaultService.getSqlMapClientTemplate().insert("omg.post.savePostMetas", params);
			}
			params.clear();
	
	    	List<Integer> termTaxonomy = null;
	    	int cataTermTaxonomyId = -1;
	    	int tagTermTaxonomyId = -1;
	    	
	    	if (CommonUtil.isEmpty(type)){
				type = "其它";
			}
			else{
				type = type.trim();
			}
			
			//System.out.println("type:" + type);
			String[] types = type.split(typeChar);
			TermsRelation termsRelation = null;
			TermsTaxonomy termsTaxonomy = null;
			Terms terms = null;
			for (int i=0, len=types.length; i < len; i++){
				//System.out.println("商品目录:" + types[i]);
				cataTermTaxonomyId = -1;
				//检查目录是否存在
				params.clear();
				params.put("taxonomy", "category");
				params.put("termName", types[i]);
				termTaxonomy = defaultService.find_iBatis("omg.post.checkTermsIsExist", params);
				if (CommonUtil.isNotEmpty(termTaxonomy)){
					cataTermTaxonomyId = termTaxonomy.get(0);
				}
				
				//保存分类目录
				termsRelation = new TermsRelation();
				if (-1 == cataTermTaxonomyId){
					terms = new Terms();
					terms.setName(types[i]);
					terms.setSlug(URLEncoder.encode(types[i]));
					defaultService.save_Hibernate_Object(terms);
					termsTaxonomy = new TermsTaxonomy();
					termsTaxonomy.setTermId(terms.getId());
					termsTaxonomy.setTaxonomy("category");
					termsTaxonomy.setDescription("商品分类目录");
					defaultService.save_Hibernate_Object(termsTaxonomy);
					cataTermTaxonomyId = termsTaxonomy.getId();
				}
				//System.out.println("cataTermTaxonomyId:"+cataTermTaxonomyId);
				termsRelation.setId(postId);
				termsRelation.setTermOrder(i);
				termsRelation.setTermTaxonomyId(cataTermTaxonomyId);
				defaultService.save_Hibernate_Object(termsRelation);
				System.out.println("商品分类目录成功:" +postId);
			}
			
			if (CommonUtil.isNotEmpty(tag)){
				String[] tags = tag.split(tagChar);
				for (int i=0,len=tags.length;i < len; i++){
					try{
						tagTermTaxonomyId = -1;
						//检查标签是否已存在
						params.clear();
						params.put("taxonomy", "post_tag");
						params.put("termName", tags[i]);
						termTaxonomy = defaultService.find_iBatis("omg.post.checkTermsIsExist", params);
						if (CommonUtil.isNotEmpty(termTaxonomy)){
							tagTermTaxonomyId = termTaxonomy.get(0);
						}
						
						//保存标签
						termsRelation = new TermsRelation();
						if (-1 == tagTermTaxonomyId){
						   terms = new Terms();
						   terms.setName(tags[i]);
						   terms.setSlug(URLEncoder.encode(tags[i]));
						   defaultService.save_Hibernate_Object(terms);
						   termsTaxonomy = new TermsTaxonomy();
						   termsTaxonomy.setTermId(terms.getId());
						   termsTaxonomy.setTaxonomy("post_tag");
						   termsTaxonomy.setDescription("商品标签");
						   defaultService.save_Hibernate_Object(termsTaxonomy);
						   tagTermTaxonomyId = termsTaxonomy.getId();
						}
						termsRelation.setId(postId);
						termsRelation.setTermOrder(i);
						termsRelation.setTermTaxonomyId(tagTermTaxonomyId);
						defaultService.save_Hibernate_Object(termsRelation);
						log.debug("商品标签成功:" +postId);
					}
					catch(Exception e){
						log.warn(e);
					}
				}
			}
	    }
		if ("1".equals(PropertiesHelper.getProperty(CrawlerStrategy.ISSENDWEIBO))){
		       //发送微博
		        wbs.send(posts.getPostTitle(), imgUrl, CrawlerStrategy.SITEURL+posts.getId());
		}
	}
		
}
